<?php
declare (strict_types = 1);

namespace app\controller;

use app\common\BaseController;
use app\service\ProcessService;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use think\facade\Db;
use think\Request;

class ProcessController extends BaseController
{
    /**
     * 肉码加工列表
     *
     * @return \think\Response
     */
    public function index(Request $request)
    {
      $page = $request->param('page', 1);
      $pageSize = $request->param('pageSize', env('pager.default.size'));
      $type = $request->param('type', '');

      $res = ProcessService::getInstance()->getProcessJoinHouse();
      // 今日是否需要编辑
      $isAdd = 0;
      $nowDate = date('Y-m-d');
      $list = [];
      // 获取原料成本
      $materialList = Db::table('house_out')
        ->field('sell_number, SUM(price * count) AS total')
        ->where('type', '=', 1)
        ->group('sell_number')
        ->select()
        ->toArray();
      $materialList = array_column($materialList, 'total', 'sell_number');
      // 获取参考总成本
      $productList = Db::table('house_in')
        ->alias('hi')
        ->join('goods g', 'g.id = hi.goods_id', 'LEFT')
        ->join('house_in_order ho', 'ho.id = hi.in_order_id', 'LEFT')
        ->field('ho.house_in_number, SUM(hi.count_in * g.price_in) AS total')
        ->where('ho.process', '=', 1)
        ->group('house_in_number')
        ->select()
        ->toArray();
      $productList = array_column($productList, 'total', 'house_in_number');
      // 编辑的数组
      $addTime = [];
      if (isset($res[0])) {
        $addTime = self::periodDate(date('Y-m-d', strtotime($res[0]['process_time'])), $nowDate);
      }
      foreach ($res as $value) {
        $value['material_total'] = 0;
        $value['default_total'] = 0;
        if (isset($materialList[$value['house_out_num']])) {
          $value['material_total'] = $materialList[$value['house_out_num']];
        }
        if (isset($productList[$value['house_in_num']])) {
          $value['default_total'] = $productList[$value['house_in_num']];
        }
        if ($isAdd) {
          $value['act'] = 0;
        } else {
          if (!$value['status']) {
            $isAdd = 1;
          }
          $value['act'] = $value['status'] ? 0 : 1;
        }
        $list[] = $value;
      }
      if ($addTime) {
        $addList = [];
        foreach ($addTime as $key => $time) {
          $add = [
            'id' => 0,
            'process_time' => $time,
            'material_total' => 0,
            'default_total' => 0,
            'act' => 0
          ];
          if ($key === 0 && !$isAdd) {
            $add['act'] = 1;
          }
          array_unshift($addList, $add);
        }
        $list = array_merge($addList, $list);
      }
      // 分页
      $count = count($list); //总条数
      $start=intval(($page - 1) * $pageSize); //偏移量，当前页-1乘以每页显示条数
      $pager = [
        'totalCount' => $count,
        'pageSize' => intval($pageSize),
        'currPage' => intval($page),
        'totalPage' => intval($count/$pageSize)+1
      ];
      $data = array_slice($list, $start, intval($pageSize));
      return $this->send200ResponseWithPager($data,$pager);
    }

    /**
     * 保存当日肉码成本
     *
     * @param  \think\Request  $request
     * @return \think\Response
     */
    public function save(Request $request)
    {
      $material = $request->param('material', []);
      $product = $request->param('product', []);
      $processTime = $request->param('processTime', []);
      if (!$processTime) {
        return $this->send400Response('缺少日期');
      }
      // 获取成本数据
      $res1 = ProcessService::getInstance()->processCount($material, $product, 1);
      if (!$res1['status']) {
        return $this->send400Response($res1['msg']);
      }
      $processTime = date('Y-m-d', strtotime($processTime));
      $res2 = ProcessService::getInstance()->saveProcess($res1['data']['house_in'], $res1['data']['house_out'], $processTime);
      if (!$res2['status']) {
        return $this->send400Response($res2['msg']);
      }
      return $this->send200Response($res1['data']['house_in']);
    }

    /**
     * 显示指定的资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function read($id)
    {
        //
    }

    /**
     * 保存更新的资源
     *
     * @param  \think\Request  $request
     * @param  int  $id
     * @return \think\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * 删除指定资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function delete($id)
    {
        //
    }

    /*
     * 获取原料肉码详情数据
     */
    public function getProcessData(Request $request) {
      $processTime = $request->param('processTime', '');
      if (!$processTime) {
        return $this->send400Response('缺少日期');
      }
      $data = ProcessService::getInstance()->getProcessDetail($processTime);
      return $this->send200Response($data);
    }

    /**
     * 计算肉码实际成本
     */
    public function processCount(Request $request) {
      $material = $request->param('material', []);
      $product = $request->param('product', []);
      if (!$material || !$product) {
        return $this->send400Response('缺少必要参数');
      }
      $res = ProcessService::getInstance()->processCount($material, $product);
      if (!$res['status']) {
        return $this->send400Response($res['msg']);
      }
      return $this->send200Response($res['data']);
    }

    /**
     * 提交当日肉码成本
     */
    public function handleSave(Request $request) {
      $material = $request->param('material', []);
      $product = $request->param('product', []);
      $processTime = $request->param('processTime', []);
      if (!$processTime) {
        return $this->send400Response('缺少日期');
      }
      // 获取成本数据
      $res1 = ProcessService::getInstance()->processCount($material, $product, 1);
      if (!$res1['status']) {
        return $this->send400Response($res1['msg']);
      }
      $processTime = date('Y-m-d', strtotime($processTime));
      $res2 = ProcessService::getInstance()->handleProcess($res1['data']['house_in'], $res1['data']['house_out'], $processTime);
      if (!$res2['status']) {
        return $this->send400Response($res2['msg']);
      }
      return $this->send200Response('ok');
    }

    /**
     * 删除某日期后的生产成本
     */
    public function deleteProcess(Request $request) {
      $processTime = $request->param('processTime', '');
      if (!$processTime) {
        return $this->send400Response('缺少日期');
      }
      $processTime = date('Y-m-d', strtotime($processTime));
      $res = ProcessService::getInstance()->deleteProcess($processTime);
      if (!$res['status']) {
        return $this->send400Response($res['msg']);
      }
      return $this->send200Response('ok');
    }

    /**
     * 导出至excel
     */
    public function export(Request $request) {
      $startTime = $request->param('startTime', '');
      $endTime = $request->param('endTime', '');
      $startTime = $startTime ? date('Y-m-d', strtotime($startTime)) : '';
      $endTime = $endTime ? date('Y-m-d', strtotime($endTime) + (24 * 60 * 60)) : '';
      $conditions = [['p.status', 1, '=']];
      if ($startTime) {
        $conditions[] = ['p.process_time', $startTime, '>='];
      }
      if ($endTime) {
        $conditions[] = ['p.process_time', $endTime, '<'];
      }
      $order = ['p.process_time' => 'ASC', 'p.id' => 'DESC'];
      // 获取时间段内数据
      $processList = ProcessService::getInstance()->getProcessJoinHouse($conditions, $order);
      $data = [];
      foreach ($processList as $process) {
        $processTime = date('Y-m-d', strtotime($process['process_time']));
        $detail = ProcessService::getInstance()->getProcessDetail($processTime);
        $material = isset($detail['materialList']) ? $detail['materialList'] : [];
        $product = isset($detail['productList']) ? $detail['productList'] : [];
        foreach ($material as $m) {
          $data[] = [
            'process_time' => $processTime,
            'type' => '原料',
            'category' => $m['category'],
            'goods' => $m['goods'],
            'unit' => $m['unit'],
            'count' => $m['count'],
            'cost' => $m['cost'],
            'total' => $m['total'],
            'default_cost' => '',
            'default_total' => ''
          ];
        }
        foreach ($product as $p) {
          $data[] = [
            'process_time' => $processTime,
            'type' => '肉码',
            'category' => $p['category'],
            'goods' => $p['goods'],
            'unit' => $p['unit_in'],
            'count' => $p['count'],
            'cost' => $p['cost'],
            'total' => $p['total_cost'],
            'default_cost' => $p['price_in'],
            'default_total' => $p['total']
          ];
        }
      }

      $spreadsheet = new Spreadsheet();
      $sheet = $spreadsheet->getActiveSheet();
      $sheet->getColumnDimension('A')->setWidth(15);
      $sheet->getColumnDimension('B')->setWidth(10);
      $sheet->getColumnDimension('C')->setWidth(10);
      $sheet->getColumnDimension('D')->setWidth(20);
      $sheet->getColumnDimension('E')->setWidth(10);
      $sheet->getColumnDimension('F')->setWidth(15);
      $sheet->getColumnDimension('G')->setWidth(15);
      $sheet->getColumnDimension('H')->setWidth(15);
      $sheet->getColumnDimension('I')->setWidth(15);
      $sheet->getColumnDimension('J')->setWidth(15);

      $sheet->setCellValue('A1', '日期');
      $sheet->setCellValue('B1', '类型');
      $sheet->setCellValue('C1', '分类');
      $sheet->setCellValue('D1', '商品名称');
      $sheet->setCellValue('E1', '单位');
      $sheet->setCellValue('F1', '数量');
      $sheet->setCellValue('G1', '实际成本');
      $sheet->setCellValue('H1', '实际总成本');
      $sheet->setCellValue('I1', '参考成本');
      $sheet->setCellValue('J1', '参考总成本');

      $row = 1;
      foreach($data as $v){
        $row++;
        $sheet->setCellValue("A{$row}", $v['process_time']);
        $sheet->setCellValue("B{$row}", $v['type']);
        $sheet->setCellValue("C{$row}", $v['category']);
        $sheet->setCellValue("D{$row}", $v['goods']);
        $sheet->setCellValue("E{$row}", $v['unit']);
        $sheet->setCellValue("F{$row}", $v['count']);
        $sheet->setCellValue("G{$row}", $v['cost']);
        $sheet->setCellValue("H{$row}", $v['total']);
        $sheet->setCellValue("I{$row}", $v['default_cost']);
        $sheet->setCellValue("J{$row}", $v['default_total']);
      }
      header("Content-type: application/octet-stream;charset=utf-8");
      header('Content-Disposition: attachment;filename="生产成本导出.xlsx"');
      header('Cache-Control: max-age=0');
      $writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xlsx');
      $writer->save('php://output');
    }

    public function periodDate($startTime, $endTime) {
      $startTime = strtotime($startTime);
      $endTime = strtotime($endTime);
      $i = 0;
      $arr = [];
      while ($startTime <= $endTime) {
        $arr[$i] = date('Y-m-d', $startTime);
        $startTime = strtotime('+1 day', $startTime);
        $i++;
      }
      array_shift($arr);
      return $arr;
    }
}

